var _ = require('lodash');
var initialState = {
    lists: {},
    carts:[]
}
function cartReduce(state = initialState, action) {
    switch (action.type) {
        case "GETLISTS":
            return Object.assign({}, state, { lists: action.data })
            break;
        case "ADDTOCART":
            /*
              先检查state.carts中是否存在action.data.id的这个对象
              如果不存在
                那么quantity购买数量为1
              如果存在
                那么先取出之前对象中的quantity，然后再在那个基础上+1
              然后再进行对象的合并操作
             */
            var pos = _.findIndex(state.carts, { '_id': action.data._id });
            if (pos === -1) {
                action.data.quantity = action.data.quantity||1;
                sessionStorage.setItem("carts",arr);
                return {
                    ...state,
                    carts: [...state.carts, action.data]
                }
            } else {
                var arr  = state.carts.slice(0);
                arr[pos].quantity ++;
                sessionStorage.setItem("carts",arr);
                return {
                    ...state,
                    carts:arr
                }
            }
            break;
            case "REMOVETOCART":
            var arr  = state.carts.slice(0);
            _.pull(arr, action.data); 
            sessionStorage.setItem("carts",arr);
            return {
                ...state,
                carts:arr
            }
            break;
            case "REMOVEALL":
            sessionStorage.setItem("carts",[]);
            return {
                ...state,
                carts:[]
            }
            break;
            case "REMOVECOUNT":
            var arr  = state.carts.slice(0);
            var pos = _.findIndex(arr, { '_id': action.data._id });
            arr[pos].quantity --;
            sessionStorage.setItem("carts",arr);
            return {
                ...state,
                carts:arr
            }
            break;
        default:
            return state;
    }
}
export default cartReduce;